package com.dmgis.qxfw.dataservice.businessservice.yyhb.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CityFcstInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecast;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecastKey;
import com.dmgis.qxfw.dataservice.businessservice.common.pojo.HighAltitude;
import com.dmgis.qxfw.dataservice.businessservice.common.pojo.MixHeightDay;
import com.dmgis.qxfw.dataservice.businessservice.common.pojo.SpecialServiceStation;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.WebCtrlData;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yyhb.service.ForecastProductServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/xthb")
public class ForecastProductController {
    private  final String operatingSystem;

    @Autowired
    public ForecastProductController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    MongoService1 mongoService=new MongoService1();
    @Autowired
    private ForecastProductServiceI Impl;

    /**
     * 查询逆温最新时间
     * @return
     */
    @RequestMapping("/tempInverInitTime")
    @ResponseBody
    public String tempInverInitTime() {
        Date date = Impl.tempInverInitTime();
        DateTime dt = new DateTime(date);
        return dt.toDateString();
    }

    /**
     * 查询逆温
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = {"/tempInver", "/tempInverWX"})
    @ResponseBody
    public String tempInver(HttpServletRequest request) throws ParseException {
        String startTime = request.getParameter("startTime");
        String timeChar = request.getParameter("time");
        String ty = request.getParameter("type");
        String type = "";
        if (!StringUtil.IsNullOrEmpty(ty)) {
            type = ty.trim();
        }
        boolean haveTemp = false;
        float T700, T850, T925, T1000, T地面;

        List<SpecialServiceStation> list = new ArrayList<SpecialServiceStation>();
        List<HighAltitude> list1 = new ArrayList<HighAltitude>();
        list = Impl.getSpecial();
        Set<String> statNames = new HashSet<String>();
        for (SpecialServiceStation s : list) {
            statNames.add(s.getStationName());
        }
        // 获取高空数据
        String date = "";
        if (startTime.length() > 0) {
            date = DateTime.parseDate(startTime).toDateString() + " " + timeChar + ":00:00";
        }
        list1 = Impl.getHighAltitude(date);
        List<Map<String, Object>> hList = new ArrayList<Map<String, Object>>();
        for (HighAltitude h : list1) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("DryBulbTemp", h.getDryBulbTemp());
            map.put("StationPress", h.getStationPress());
            map.put("StationID", h.getStationID());
            map.put("StationName", h.getStationName());
            hList.add(map);
        }

        // 获取地面数据
        list1.clear();
        list1 = Impl.getGroundElements(date);
        List<Map<String, Object>> gList = new ArrayList<Map<String, Object>>();
        for (HighAltitude h : list1) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("DryBulbTemp", h.getDryBulbTemp());
            map.put("StationPress", h.getStationPress());
            map.put("StationID", h.getStationID());
            map.put("StationName", h.getStationName());
            gList.add(map);
        }

        List<Map<String, String>> tempList = new ArrayList<Map<String, String>>();
        for (String str : statNames) {
            T700 = 9999;
            T850 = 9999;
            T925 = 9999;
            T1000 = 9999;
            T地面 = 9999;
            String d7_地 = "", d8_地 = "", d9_地 = "", d10_地 = "", d7_8 = "", d7_9 = "", d7_10 = "", d8_9 = "", d8_10 = "",
                    d9_10 = "";
            if (hList.size() > 0 && gList.size() > 0) {
                for (Map<String, Object> map : hList) {
                    for (Map<String, Object> hmap : gList) {
                        if (String.valueOf(map.get("StationName")).contains(str)
                                || String.valueOf(hmap.get("StationName")).contains(str)) {
                            String s1 = String.valueOf(map.get("StationPress"));
                            if (Float.valueOf(s1) == 700) {
                                T700 = Float.valueOf(map.get("DryBulbTemp").toString());
                                T700 = T700 == -65535 ? 9999 : T700;
                            } else if (Float.valueOf(String.valueOf(map.get("StationPress"))) == 850) {
                                T850 = Float.valueOf(String.valueOf(map.get("DryBulbTemp")));
                                T850 = T850 == -65535 ? 9999 : T850;
                            } else if (Float.valueOf(String.valueOf(map.get("StationPress"))) == 925) {
                                T925 = Float.valueOf(String.valueOf(map.get("DryBulbTemp")));
                                T925 = T925 == -65535 ? 9999 : T925;
                            } else if (Float.valueOf(String.valueOf(map.get("StationPress"))) == 1000) {
                                T1000 = Float.valueOf(String.valueOf(map.get("DryBulbTemp")));
                                T1000 = T1000 == -65535 ? 9999 : T1000;
                            }
                            T地面 = Float.valueOf(String.valueOf(hmap.get("DryBulbTemp")));
                            T地面 = T地面 == -65535 ? 9999 : T地面;
                        }
                    }
                }

                // 计算
                if (T地面 != 9999) {
                    if (T700 != 9999)
                        d7_地 = String.valueOf((Math.round(((T700 - T地面) * 10))) / 10);
                    else
                        d7_地 = "0";

                    if (T850 != 9999)
                        d8_地 = String.valueOf((Math.round(((T850 - T地面) * 10))) / 10);
                    else
                        d8_地 = "0";

                    if (T925 != 9999)
                        d9_地 = String.valueOf((Math.round(((T925 - T地面) * 10))) / 10);
                    else
                        d9_地 = "0";

                    if (T1000 != 9999)
                        d10_地 = String.valueOf((Math.round(((T1000 - T地面) * 10))) / 10);
                    else
                        d10_地 = "0";
                }

                if (T700 != 9999) {
                    if (T850 != 9999)
                        d7_8 = String.valueOf((Math.round(((T700 - T850) * 10))) / 10);
                    else
                        d7_8 = "0";

                    if (T925 != 9999)
                        d7_9 = String.valueOf((Math.round(((T700 - T925) * 10))) / 10);
                    else
                        d7_9 = "0";

                    if (T1000 != 9999)
                        d7_10 = String.valueOf((Math.round(((T700 - T1000) * 10))) / 10);
                    else
                        d7_10 = "0";
                }

                if (T850 != 9999) {
                    if (T925 != 9999)
                        d8_9 = String.valueOf((Math.round(((T850 - T925) * 10))) / 10);
                    else
                        d8_9 = "0";

                    if (T1000 != 9999)
                        d8_10 = String.valueOf((Math.round(((T850 - T1000) * 10))) / 10);
                    else
                        d8_10 = "0";
                }

                if (T925 != 9999) {
                    if (T1000 != 9999)
                        d9_10 = String.valueOf((Math.round(((T925 - T1000) * 10))) / 10);
                    else
                        d9_10 = "0";
                }

                Map<String, String> m = new HashMap<String, String>();
                m.put("站点名称", str);
                m.put("T700-T地面", d7_地);
                m.put("T850-T地面", d8_地);
                m.put("T925-T地面", d9_地);
                m.put("T1000-T地面", d10_地);
                m.put("T700-T1000", d7_10);
                m.put("TT850-T1000", d8_10);
                m.put("T925-T1000", d9_10);
                m.put("T700-T925", d7_9);
                m.put("T850-T925", d8_9);
                m.put("T700-T850", d7_8);
                tempList.add(m);
                haveTemp = true;
            }
        }
        String strstaName = "";
        for (Map<String, String> m : tempList) {
            strstaName = m.get("站点名称").toString();
            for (String s : m.keySet()) {
                if (m.get(s).toString() != "-" && !"站点名称".equals(s)) {
                    if (!"".equals(m.get(s)) && Float.valueOf(m.get(s)) > 0) {
                        haveTemp = true;
                        break;
                    }
                }
            }
        }
        String start = DateTime.parseDate(startTime).toDateTimeString();
        if (haveTemp) {
            Impl.delTempInver(start);
            Impl.insertTempInver(strstaName, start, timeChar, "1");
        }
        String xValue = "['T700-T地面','T850-T地面','T925-T地面','T700-T925','T850-T925','T700-T850']";
        String yValue = "";
        String y = "";
        String listData = "[";
        for (Map<String, String> tl : tempList) {

            yValue = "{name:'" + tl.get("站点名称") + "',data:" + "[" + division(Integer.parseInt(tl.get("T700-T地面")), 10)
                    + "," + division(Integer.parseInt(tl.get("T850-T地面")), 10) + ","
                    + division(Integer.parseInt(tl.get("T925-T地面")), 10) + ","
                    + division(Integer.parseInt(tl.get("T700-T925")), 10) + ","
                    + division(Integer.parseInt(tl.get("T850-T925")), 10) + ","
                    + division(Integer.parseInt(tl.get("T700-T850")), 10) + "]},";
            y += yValue;

            listData += "{\"station\":\"" + tl.get("站点名称") + "\",\"T700-T地面\":\""
                    + division(Integer.parseInt(tl.get("T700-T地面")), 10) + "\",\"T850-T地面\":\""
                    + division(Integer.parseInt(tl.get("T850-T地面")), 10) + "\",\"T925-T地面\":\""
                    + division(Integer.parseInt(tl.get("T925-T地面")), 10) + "\",\"T700-T925\":\""
                    + division(Integer.parseInt(tl.get("T700-T925")), 10) + "\",\"T850-T925\":\""
                    + division(Integer.parseInt(tl.get("T850-T925")), 10) + "\",\"T700-T850\":\""
                    + division(Integer.parseInt(tl.get("T700-T850")), 10) + "\"},";
        }
        if (y.endsWith(",")) {
            y = y.substring(0, y.length() - 1);
        }
        y = "[" + y + "]";
        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData = listData + "]";
        String dataTable = "[]";
        if (haveTemp)
            dataTable = "[" + startTime + "]";
        String title = "['" + startTime + "日" + timeChar + "时逆温曲线图" + "']";
        String temp = dataTable + "|" + xValue + "|" + y + "|" + title + "|['" + type + "']|" + listData;
        return temp;
    }





    /**
     * 查询逆温预报最新时间
     * @return
     */
    @RequestMapping("/tempInverYBInitTime")
    @ResponseBody
    public String tempInverYBInitTime() {
        Date date = Impl.tempInverYBInitTime();
        DateTime dt = new DateTime(date);
        return dt.toDateString();
    }

    /**
     * 查询逆温预报
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("/tempInverYB")
    @ResponseBody
    public String tempInverYB(HttpServletRequest request) throws ParseException {
        String startTime = request.getParameter("startTime");
        String timeChar = request.getParameter("time");
        String type = request.getParameter("type").trim();
        String hourorday = request.getParameter("hourorday").trim();
        List<temp_inversionyb> mixList = new ArrayList<temp_inversionyb>();
         mixList = Impl.getYBTempInversion(startTime, timeChar, hourorday);
        boolean haveTemp = false;
        String xValue = "[";
        String yValue = "";
        String y = "";
        String listData = "[";
        String types = "";
        for (temp_inversionyb mh : mixList) {
            if (!types.contains(mh.getType())) {
                types += mh.getType() + ",";
                yValue = "{name:'" + mh.getType() + "',data:" + "[";
                for (temp_inversionyb hn : mixList) {
                    if (mh.getType().equals(hn.getType())) {
                       String date1 = new DateTime(hn.getDatechar()).toDateTimeString("yyyy-MM-dd HH");
                        xValue += "'" + date1 + "',";
                        yValue += hn.getTempinversion() + ",";
                        listData += "{\"date\":\"" + date1 + "\",\"Tempinversion\":\"" + hn.getTempinversion()
                                + "\",\"stationname\":\"" + hn.getStationname() + "\",\"type\":\"" + mh.getType()
                                + "\"},";
                        haveTemp = true;
                    }
                }
                yValue += "]},";
                y += yValue;
            }
        }
        if (xValue.endsWith(",")) {
            xValue = xValue.substring(0, xValue.length() - 1);
        }
        xValue += "]";

        if (y.endsWith(",")) {
            y = y.substring(0, y.length() - 1);
        }
        y = "[" + y + "]";

        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData += "]";
        String dataTable = "[]";
        if (haveTemp)
            dataTable = "[" + startTime + "]";
        String title = "['" + startTime + "日" + timeChar + "时逆温逐小时预报曲线图" + "']";
        if (hourorday.equals("day")) {
            title = "['" + startTime + "日" + timeChar + "时逆温逐日预报曲线图" + "']";
        }
        String temp = dataTable + "|" + xValue + "|" + y + "|" + title + "|['" + type + "']|" + listData;
        return temp;
    }

    /**
     * 查询首页逆温预报
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("/tempInverSyYB")
    @ResponseBody
    public String tempInverSyYB(HttpServletRequest request) throws ParseException {
        String startTime = request.getParameter("startTime");
        String timeChar = request.getParameter("time");
        String type = request.getParameter("type").trim();
        String hourorday = request.getParameter("hourorday").trim();
        List<temp_inversionyb> mixList = new ArrayList<temp_inversionyb>();
        mixList = Impl.getYBTempInversion(startTime, timeChar, hourorday);
        boolean haveTemp = false;
        String xValue = "[";
        String yValue = "";
        String y = "";
        String listData = "[";
        String types = "";
        for (temp_inversionyb mh : mixList) {
            if (mh.getType().equals("T1000-T地面")) {
                if (!types.contains(mh.getType())) {
                    types += mh.getType() + ",";
                    yValue = "{name:'" + mh.getType() + "',data:" + "[";
                    for (temp_inversionyb hn : mixList) {
                        if (mh.getType().equals(hn.getType()) && hn.getType().equals("T1000-T地面")) {
                            String date1 = new DateTime(hn.getDatechar()).toDateTimeString("yyyy-MM-dd HH").substring(8,13);
                            xValue += "'" + date1 + "',";
                            yValue += hn.getTempinversion() + ",";
                            listData += "{\"date\":\"" + date1 + "\",\"Tempinversion\":\"" + hn.getTempinversion()
                                    + "\",\"stationname\":\"" + hn.getStationname() + "\",\"type\":\"" + mh.getType()
                                    + "\"},";
                            haveTemp = true;
                        }
                    }
                    yValue += "]},";
                    y += yValue;
                }
            }
        }
        if (xValue.endsWith(",")) {
            xValue = xValue.substring(0, xValue.length() - 1);
        }
        xValue += "]";

        if (y.endsWith(",")) {
            y = y.substring(0, y.length() - 1);
        }
        y = "[" + y + "]";

        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData += "]";
        String dataTable = "[]";
        if (haveTemp)
            dataTable = "[" + startTime + "]";
        String title = "['" + startTime + "日" + timeChar + "时逆温逐小时预报曲线图" + "']";
        if (hourorday.equals("day")) {
            title = "['" + startTime + "日" + timeChar + "时逆温逐日预报曲线图" + "']";
        }
        String temp = dataTable + "|" + xValue + "|" + y + "|" + title + "|['" + type + "']|" + listData;
        return temp;
    }

    public static String division(int a, int b) {
        String result = "";
        float num = (float) a / b;
        DecimalFormat df = new DecimalFormat("0.0");
        result = df.format(num);
        return result;
    }

    /**
     * 查询混合层高度最新时间
     * @return
     */
    @RequestMapping("/mixHeightInitTime")
    @ResponseBody
    public String mixHeightInitTime() {
        Date date = Impl.mixHeightInitTime();
        DateTime dt = new DateTime(date);
        return dt.toDateString();
    }


    /**
     * 查询混合层高度
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = {"/getMixingHeight", "/getMixingHeightWX"})
    @ResponseBody
    public String getMixingHeight(HttpServletRequest request) throws Exception {
        String date = request.getParameter("dateTime");
        String ty = request.getParameter("type");
        String type = "";
        if (!StringUtil.IsNullOrEmpty(ty)) {
            type = ty.trim();
        }
        String radio = request.getParameter("hourOrDay");
        String dateTime = DateTime.parseDate(date).toDateString();
        String dateTime1 = DateTime.parseDate(dateTime).AddDays(7).toDateString();
        if ("时".equals(radio)) {
            dateTime1 = DateTime.parseDate(dateTime).AddDays(1).toDateString();
        }
        List<MixHeightDay> mixList = new ArrayList<MixHeightDay>();
        mixList = Impl.getMixHeightDay(dateTime, dateTime1, radio);
        String xValue = "[";
        String yValue = "[{name:'混合层高度',data:[";
        String listData = "[";
        for (MixHeightDay mh : mixList) {
            String date1 = "";
            if ("时".equals(radio)) {
                date1 = new DateTime(mh.getDateChar()).toDateTimeString("yyyy-MM-dd HH");
            } else {
                date1 = new DateTime(mh.getDateChar()).toDateString();
            }
            xValue += "'" + date1 + "',";
            yValue += mh.getMixingHeightDay() + ",";

            listData += "{\"date\":\"" + date1 + "\",\"MixingHeightDay\":\"" + mh.getMixingHeightDay()
                    + "\",\"type\":\"" + 24 + "\"},";
        }
        if (xValue.endsWith(",")) {
            xValue = xValue.substring(0, xValue.length() - 1);
        }
        xValue += "]";
        if (yValue.endsWith(",")) {
            yValue = yValue.substring(0, yValue.length() - 1);
        }
        yValue += "]}]";

        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData += "]";
        String title = "";
        if ("时".equals(radio)) {
            title = "['" + dateTime + "日到" + dateTime1 + "混合层高度" + "']";
        } else {
            title = "['" + dateTime + "日到" + dateTime1 + "混合层高度" + "']";
        }
        String temp = xValue + "|" + yValue + "|" + title + "|['" + type + "']|" + listData;
        return temp;
    }


    /**
     * 查询混合层高度实况
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSKMixingHeight")
    @ResponseBody
    public String getSKMixingHeight(HttpServletRequest request) throws Exception {
        String date = request.getParameter("dateTime") + " 00:00:00";
        String type = request.getParameter("type").trim();
        String dateTime = DateTime.parseDate(date).toDateTimeString();
        String dateTime1 = DateTime.parseDate(dateTime).AddHours(24).toDateTimeString();
        List<MixHeightDay> mixList = new ArrayList<MixHeightDay>();
        mixList = Impl.getMixHeightSK(dateTime, dateTime1);
        String xValue = "[";
        String yValue = "[{name:'混合层高度',data:[";
        String listData = "[";
        for (MixHeightDay mh : mixList) {
            String date1 = new DateTime(mh.getDateChar()).toDateTimeString();
            xValue += "'" + date1 + "',";
            yValue += mh.getMixingHeightDay() + ",";

            listData += "{\"date\":\"" + date1 + "\",\"MixingHeightDay\":\"" + mh.getMixingHeightDay()
                    + "\",\"type\":\"" + 24 + "\"},";
        }
        if (xValue.endsWith(",")) {
            xValue = xValue.substring(0, xValue.length() - 1);
        }
        xValue += "]";
        if (yValue.endsWith(",")) {
            yValue = yValue.substring(0, yValue.length() - 1);
        }
        yValue += "]}]";

        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData += "]";
        String title = "['" + dateTime + "到" + dateTime1 + "混合层高度" + "']";
        String temp = xValue + "|" + yValue + "|" + title + "|['" + type + "']|" + listData;
        return temp;
    }

    /**
     * 查询气象要素最新时间
     * @return
     */
    @RequestMapping("/metEleInitTime")
    @ResponseBody
    public Object metEleInitTime() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        township_forecasttemp newestDate = Impl.metEleInitTime();
        // 加载列表
        String timechar = newestDate.getTimechar();
        String datechar = new DateTime(newestDate.getDatechar()).toDateString();
        arrayList.add(timechar);
        arrayList.add(datechar);
        return arrayList;
    }

    /**
     * 查询气象要素
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getMetElement" )
    @ResponseBody
    public String getMetElement(HttpServletRequest request) throws Exception {
        System.out.println("startTime: "+request.getParameter("startTime"));
        System.out.println("time: "+request.getParameter("time"));
        System.out.println("aging: "+request.getParameter("aging"));
        System.out.println("stationName: "+request.getParameter("stationName"));
        System.out.println("element: "+request.getParameter("element"));
        System.out.println("type: "+request.getParameter("type"));

        String startTime = request.getParameter("startTime");
        String time = request.getParameter("time");
        String[] agings=new String[7];
        agings = request.getParameterValues("aging");
        if (agings[0].equals("24")){
            agings = new String[] { "24"};
        }
        if (agings[0].equals("48")){
            agings = new String[] { "24", "48" };
        }
        if (agings[0].equals("72")){
            agings = new String[] { "24", "48", "72" };
        }
        if (agings[0].equals("96")){
            agings = new String[] { "24", "48", "72", "96" };
        }
        if (agings[0].equals("120")){
            agings = new String[] { "24", "48", "72", "96", "120"};
        }
        if (agings[0].equals("144")){
            agings = new String[] { "24", "48", "72", "96", "120", "144" };
        }
        if (agings[0].equals("168")){
            agings = new String[] { "24", "48", "72", "96", "120", "144","168" };
        }
        String[] stationNames = request.getParameterValues("stationName");
        String element = request.getParameter("element").trim();
        String ele = "";
        String type = request.getParameter("type").trim();
        String xValue = "[";
        String listData = "[";
        Field field = null;
        field = township_forecasttemp.class.getDeclaredField(element);
        field.setAccessible(true);
        switch (element) {
            case "winds":
                ele = "风速";
                break;
            case "windd":
                ele = "风向";
                break;
            case "rain":
                ele = "降水量";
                break;
            case "cloud":
                ele = "云量";
                break;
            case "maxtemp":
                ele = "最高温度";
                break;
            case "mintemp":
                ele = "最低温度";
                break;
            case "humid":
                ele = "相对湿度";
                break;
        }
        if (agings == null) {
            agings = new String[] { "24", "48", "72", "96", "120", "144", "168" };
        }
        if (stationNames == null) {
            stationNames = new String[] { DbConfig.STATIONNAME};
        }
        // 时效、x轴
        String tit = "";
        String dates = "(";
        List<String> dateList = new ArrayList<String>();
        for (int k = 0; k < agings.length; k++) {
            int i = Integer.valueOf(agings[k]) / 24;
            dateList.add(agings[k].trim());
            xValue += "'" + DateTime.parseDate(startTime).AddDays(i).toDateString() + "',";
            tit += agings[k] + "-";
        }
        if (dates.endsWith(",")) {
            dates = dates.substring(0, dates.length() - 1);
        }
        dates = dates + ")";
        if (xValue.endsWith(",")) {
            xValue = xValue.substring(0, xValue.length() - 1);
        }
        xValue = xValue + "]";

        // 站点
        String stations = "(";
        for (String s : stationNames) {
            stations += "'" + s + "'" + ",";
        }
        if (stations.endsWith(",")) {
            stations = stations.substring(0, stations.length() - 1);
        }
        stations = stations + ")";

        // Ntimes
        String nT = "";
        for (String s : dateList) {
            nT += "'" + s + "',";
        }
        if (nT.endsWith(",")) {
            nT = nT.substring(0, nT.length() - 1);
        }
        // 查询
        List<String> strList = new ArrayList<String>();
        List<String> ftrList = new ArrayList<String>();
        List<township_forecasttemp> eleList = new ArrayList<township_forecasttemp>();
        eleList = Impl.getMetElementInfo(startTime, time, stations);
        if (eleList.size() > 0) {
            Iterator<township_forecasttemp> it = eleList.iterator();
            while (it.hasNext()) {
                if (!dateList.contains(it.next().getNtimes().toString().trim())) {
                    it.remove();
                }
            }
        }
        String fenxiang="";
        for (String s : stationNames) {
            String name = s.trim();
            fenxiang="{name:'"+name+ "',data:" + "[";
            String yValue = "{name:'" + name + "',data:" + "[";
            for (township_forecasttemp me : eleList) {
                DateTime dt = new DateTime(me.getDatechar());
                if (me.getStationname().trim().equals(name)) {
                    switch (element) {
                        case "winds":
                            yValue += me.getWinds() + ",";
                            WebCtrlData w=new WebCtrlData();
                            fenxiang +="'"+ w.GetAllFx(me.getWindd().toString())+"'"+",";

                            break;
                        case "windd":
                            yValue += me.getWindd() + ",";
                            WebCtrlData f=new WebCtrlData();
                            fenxiang +="'"+ f.GetAllFx(me.getWindd().toString())+"'"+",";
                            break;
                        case "rain":
                            yValue += me.getRain() + ",";
                            break;
                        case "cloud":
                            yValue += me.getCloud() + ",";
                            break;
                        case "maxtemp":
                            yValue += me.getMaxtemp() + ",";
                            break;
                        case "mintemp":
                            yValue += me.getMintemp() + ",";
                            break;
                        case "humid":
                            yValue += me.getHumid() + ",";
                            break;
                    }
                }
                listData += "{\"station\":\"" + me.getStationname() + "\",\"date\":\"" + dt.toDateString() + " "
                        + me.getNtimes() + "\",\"other\":\"" + field.get(me) + "\"},";
            }

            if (yValue.endsWith(",")) {
                yValue = yValue.substring(0, yValue.length() - 1);
            }
            yValue = yValue + "]},";
            strList.add(yValue);
            yValue = "";
            if (fenxiang.endsWith(",")) {
                fenxiang = fenxiang.substring(0, fenxiang.length() - 1);
            }
            fenxiang = fenxiang + "]},";
            ftrList.add(fenxiang);
            fenxiang = "";
        }

        String y = "[";
        for (String ss : strList) {
            y += ss;
        }
        if (y.endsWith(",")) {
            y = y.substring(0, y.length() - 1);
        }
        y = y + "]";

        String f1 = "[";
        for (String ss : ftrList) {
            f1 += ss;
        }
        if (f1.endsWith(",")) {
            f1 = f1.substring(0, f1.length() - 1);
        }
        f1 = f1 + "]";

        if (tit.endsWith("-")) {
            tit = tit.substring(0, tit.length() - 1);
        }
        if (listData.endsWith(",")) {
            listData = listData.substring(0, listData.length() - 1);
        }
        listData = listData + "]";

        Integer a=Integer.parseInt(agings[agings.length-1])/24;
        String s = DateTime.parseDate(startTime).AddDays(a).toDateString();
        String start = DateTime.parseDate(startTime).toDateString();
        String title = "['" + start + "日至" + s + "日" + ele + "曲线图" + "']";

        String temp = xValue + "|" + y + "|" + title + "|['" + type + "']|" + listData + "|['" + ele + "']|"+f1;
        return temp;
    }

    /**
     * 初始化天气分析最新时间
     *
     * @param
     * @return
     * @author
     * @date 2019/12/26
     **/
    @RequestMapping("/InitWeatherImagetime")
    @ResponseBody
    public Object InitWeatherImagetime() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(Impl.InitWeatherImagetime());
        result.add(endDate.AddHours(-12).toDateTimeString());
        result.add(endDate.toDateTimeString());
        return result;
    }


    /**
     * 获取天气分析图片
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showWeatherImg")
    @ResponseBody
    public Object showWeatherImg(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate")+":00:00";
        String endDate = request.getParameter("endDate")+":00:00";
        String type = request.getParameter("type");
        String level = request.getParameter("level");
        List<weatherchart> base_products = Impl.showWeatherImg(startDate, endDate,level,type);
        List<String> result = new ArrayList<String>();
        String servicePath = "";// 服务器文件
        for(weatherchart product : base_products){
            String id = product.getId().toString();// 获取编号
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\WeatherAnalysis\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/WeatherAnalysis/";// 临时文件目录
            }

            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_hhmmss");
            String format1 = format.format(product.getObservtime());
            String fileName =format1+"_"+product.getArrangement()+"_"+product.getType()+".jpg";// 文件名
            servicePath = urlpath + fileName;// 服务器路径
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\WeatherAnalysis\\" + fileName;
                }else {
                    servicePath = "Temp/WeatherAnalysis/" + fileName;
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("table_id", id);
                map.put("collectionName", "weatherchart_jpg_file");
                byte[] data =mongoService.selectData(map);
                if (data == null) {
                    servicePath = "../../../images/nopic.jpg";
                }else {
                    FileUtil.bytesToFile(data, servicePath);

                    if (operatingSystem.equals("Windows")){
                        servicePath = "Temp\\WeatherAnalysis\\" + fileName;
                    }else {
                        servicePath = "Temp/WeatherAnalysis/" + fileName;
                    }
                }
            }
            servicePath = servicePath.replace("\\", "/");
            result.add(servicePath);
        }
        return result;
    }

    /**
     * 查询高空预报最新时间
     * @return
     */
    @RequestMapping("/initHighelements")
    @ResponseBody
    public Object initHighelements(){
        ArrayList<Object> arrayList = new ArrayList<Object>();/* object各种类型数据 */
        Date date = Impl.initHighelements();
        DateTime observtime = new DateTime(date);// DateTime类型
        String startDate = observtime.AddHours(-1).toDateTimeString();// String类型
        String endDate = observtime.toDateTimeString();// String类型
        arrayList.add(startDate);// 开始时间
        arrayList.add(endDate);// 结束时间
        return arrayList;
    }

    /**
     * 查询高空预报
     * @return
     */
    @RequestMapping("/GetHighelements")
    @ResponseBody
    public  List<high_elements> GetHighelements(HttpServletRequest request){
        List<high_elements> result = new ArrayList<>();
        String date = request.getParameter("date")+":00:00";
        String press = request.getParameter("press");
        List<high_elements> elements = Impl.GetHighelements(date,press);
        WebCtrlData webCtrlData = new WebCtrlData();
        for (high_elements h:elements){
            high_elements ele = new high_elements();
            ele.setStationid(h.getStationid());
            ele.setStationname(h.getStationname());
            ele.setObservtime(h.getObservtime());
            ele.setLongitude(h.getLongitude());
            ele.setLatitude(h.getLatitude());
            ele.setAltitude(h.getAltitude());
            ele.setCity(h.getCity());
            ele.setCounty(h.getCounty());
            ele.setStationpress(h.getStationpress());
            ele.setDrybulbtemp(h.getDrybulbtemp());
            ele.setDewpointtemp(h.getDewpointtemp());
            ele.setWindvelocity(h.getWindvelocity());
            ele.setFX(webCtrlData.GetAllFx(h.getWinddirect().toString()));
            result.add(ele);
        }
        return result;
    }

    /**
     * 高空站时统计图
     * @author
     * @date 2019/12/27
     * @param
     * @return
     **/
    @RequestMapping("/HighaddRWChart")
    @ResponseBody
    public Object HighaddRWChart(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String element = request.getParameter("element");
        String chartType = request.getParameter("chartType");
        String type = request.getParameter("type");
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(chartType);
        List<ActualData> resultList = Impl.qxElementQuery(elemQuery,type);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (ActualData actualData : resultList) {
            String stationName = actualData.getStationName().trim();
            if (stationName.equals(resultList.get(0).getStationName().trim())) {
                if (elemQuery.getDaytype()!=null&&elemQuery.getDaytype()!=""){
                    hours.add(new DateTime(actualData.getDateTime()).GetMonth()+"-"+new DateTime(actualData.getDateTime()).GetDay());
                }else {
                    hours.add(new DateTime(actualData.getDateTime()).GetDay()+"日"+new DateTime(actualData.getDateTime()).GetHour()+"时");
                }
            }
            double value = 0d;
            switch (element) {
                case "temp":
                    value = actualData.getTemp();
                    break;
                case "winds":
                    value = actualData.getWinds();
                    break;
                case "pressure":
                    value = actualData.getPressure();
                default:
                    break;
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();
                values.add(value);
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(value);
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }

    /**
     * 高空站日均统计图
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     * @author dsq
     * @date 2018年7月13日
     */
    @RequestMapping(value = {"/HighaddDayChart", "/HighaddDayChart", "/HighaddDayChart20"})
    @ResponseBody
    public Object HighaddDayChart(HttpServletRequest request, Model model) throws ParseException {
        Date startDate = DateTime.parseDate(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDate(request.getParameter("endDate")).toDate();

        String element = request.getParameter("element");
        String type = request.getParameter("type");
        String chartType = request.getParameter("chartType");
        if (request.getRequestURI().contains("/addDayChart08")) {
            String date1 = new DateTime().now().AddDays(-6).toDateString() + " 08:00:00";
            startDate = DateTime.parseDateTime(date1).toDate();
            String date2 = new DateTime().now().toDateString() + " 08:00:00";
            endDate = DateTime.parseDateTime(date2).toDate();
        } else if (request.getRequestURI().contains("/addDayChart20")) {
            String date1 = new DateTime().now().AddDays(-6).toDateString() + " 20:00:00";
            startDate = DateTime.parseDateTime(date1).toDate();
            String date2 = new DateTime().now().toDateString() + " 20:00:00";
            endDate = DateTime.parseDateTime(date2).toDate();
        }
        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setType(chartType);
        elemQuery.setDaytype("日均");
        List<ActualData> resultList = Impl.qxElementQuery(elemQuery,type);
        // 处理成曲线图
        List<Integer> days = new ArrayList<Integer>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (ActualData actualData : resultList) {
            String stationName = actualData.getStationName().trim();
            if (stationName.equals(resultList.get(0).getStationName().trim())) {
                days.add(new DateTime(actualData.getDateTime()).GetDay());
            }
            double value = 0d;
            switch (element) {
                case "rain":
                    value = actualData.getRain();
                    break;
                case "temp":
                    value = actualData.getTemp();
                    break;
                case "winds":
                    value = actualData.getWinds();
                    break;
                case "humid":
                    value = actualData.getHumid();
                    break;
                case "pressure":
                    value = actualData.getPressure();
                default:
                    break;
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();
                values.add(value);
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(value);
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(days);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }

    @RequestMapping(value = { "/getMetElement1", "/getMetElementWX" })
    @ResponseBody
    public Object getMetElement1(HttpServletRequest request) throws Exception {
        String startTime = request.getParameter("startTime");
        String time = request.getParameter("sc");
        String[] stationNames = request.getParameterValues("stationName");
        String element = request.getParameter("element").trim();
        if (stationNames == null) {
            stationNames = new String[] {DbConfig.STATIONNAME};
        }
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        List<String> hours = new ArrayList<String>();
        Map<String,List<Double>> infomap=new HashMap();
        try {
            selectKey.setTimeChar(time);
            selectKey.setDateChar(DateTime.parseDate(startTime).toDate());
            List<TownshipForecast> fcstList = Impl.getfcstPoint(selectKey,stationNames);
            int count = fcstList.toArray().length;
            List<Double> values=new ArrayList<>();
            List<Double> values1=new ArrayList<>();
            List<Double> values2=new ArrayList<>();
            for (int i = 0; i < fcstList.size();i++) {
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(fcstList.get(i).getDateChar());
                calendar.add(Calendar.DATE,fcstList.get(i).getNTimes()/24);
                SimpleDateFormat simpleDateFormat1=new SimpleDateFormat("MM-dd");
                String tempdate=simpleDateFormat1.format(calendar.getTime());
                hours.add(tempdate);
                switch (element) {
                    case "winds":
                        values.add(fcstList.get(i).getWindS());
                        break;
                    case "rain":
                        values.add(fcstList.get(i).getRain());
                        break;
                    case "cloud":
                        values.add(fcstList.get(i).getCloud());
                        break;
                    case "maxtemp":
                        values.add(fcstList.get(i).getMaxTemp());
                        break;
                    case "mintemp":
                        values.add(fcstList.get(i).getMinTemp());
                        break;
                    case "humid":
                        values.add(fcstList.get(i).getHumid());
                        break;
                }
            }
            infomap.put(fcstList.get(0).getStationName(),values);

        }catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : infomap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(infomap.get(key));
            result.add(tempArr);
        }
        return result;
    }

}
